package com.ai.common.http;

import com.ai.common.http.dto.FluxMessage;
import com.ai.sevice.ai.remote.CompletionsRequest;
import com.ai.sevice.ai.remote.CompletionsResponse;
import com.ai.sevice.ai.remote.Message;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;

@Slf4j
@Component
public class TransferStationClient {

    private org.springframework.web.reactive.function.client.WebClient webClient =
            org.springframework.web.reactive.function.client.WebClient.builder()
                    .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                    .build();
    @Autowired
    private RestTemplate restTemplate;

    //private static final String OPEN_AI_HOST_URL = "http://www.aixlb.top:8090/";
    private static final String OPEN_AI_HOST_URL = "http://45.155.220.234:8090/";

    public CompletionsResponse completions(CompletionsRequest request, String token){
        if (request == null || StringUtils.isBlank(token)){
            return null;
        }
        String url = OPEN_AI_HOST_URL + "transfer/openAi/completions";
        //设置请求头参数
        HttpHeaders head = new HttpHeaders();
        head.add("Content-Type","application/json");
        head.add("Authorization",token);
        //封装请求参数
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(request),head);
        ResponseEntity<CompletionsResponse> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, entity, CompletionsResponse.class,new HashMap<>());
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return responseEntity.getBody();
    }

    /**
     * flux
     * @param request
     * @param token
     * @return
     */
    public Flux<String> completionsFlux(CompletionsRequest request,String token) {
        if (request == null){
            Flux<String> just = Flux.just(JSON.toJSONString(new FluxMessage("请求参数不能为空",null)),
                    JSON.toJSONString(new FluxMessage("",true)));
            return just;
        }
        String url = OPEN_AI_HOST_URL + "transfer/openAi/completionsFlux";

        return webClient.post()
                .uri(url)
                .header(HttpHeaders.AUTHORIZATION, token)
                .bodyValue(JSON.toJSONString(request))
                .retrieve()
                .bodyToFlux(String.class)
                .onErrorResume(WebClientResponseException.class, ex -> {
                    HttpStatus status = ex.getStatusCode();
                    String res = ex.getResponseBodyAsString();
                    log.error("completionsFlux error: {} {}", status, res);
                    return Mono.error(new RuntimeException(res));
                });
    }

    //////////////////////////////////////////////////////////////////////////////////////
    private static final String HOST_URL = "http://www.aixlb.top:8080/";

    public CompletionsResponse apiCompletions(CompletionsRequest request,String token){
        if (request == null || StringUtils.isBlank(token)){
            return null;
        }
        String url = HOST_URL + "transferStation/completions";
        //设置请求头参数
        HttpHeaders head = new HttpHeaders();
        head.add("Content-Type","application/json");
        head.add("Authorization",token);
        //封装请求参数
        HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(request),head);
        ResponseEntity<CompletionsResponse> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, entity, CompletionsResponse.class,new HashMap<>());
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return responseEntity.getBody();
    }

    /**
     * flux
     * @param request
     * @param token
     * @return
     */
    public Flux<String> completionsFlux2(CompletionsRequest request,String token) {
        if (request == null){
            Flux<String> just = Flux.just(JSON.toJSONString(new FluxMessage("请求参数不能为空",null)),
                    JSON.toJSONString(new FluxMessage("",true)));
            return just;
        }
        String url = HOST_URL + "transferStation/completionsFlux";

        return webClient.post()
                .uri(url)
                .header(HttpHeaders.AUTHORIZATION, token)
                .bodyValue(JSON.toJSONString(request))
                .retrieve()
                .bodyToFlux(String.class)
                .onErrorResume(WebClientResponseException.class, ex -> {
                    HttpStatus status = ex.getStatusCode();
                    String res = ex.getResponseBodyAsString();
                    log.error("completionsFlux error: {} {}", status, res);
                    return Mono.error(new RuntimeException(res));
                });
    }


}
